import { reqGetCode, reqRegisterUser, reqLoginUser, reqGetUserInfo,reqLogout } from "@/api"
import { setToken,getToken,removeToken } from "@/utils/token"
const state = {
    code: "",
    token: getToken(),
    userInfo: {}
}
const actions = {
    async getCode({commit},phone) {
        let result = await reqGetCode(phone)
        if (result.data.code == 200) {
            commit("GETCODE", result.data.data);
            return "ok"    
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async registerUser(_, data) {
        let result = await reqRegisterUser(data)
        if (result.data.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async loginUser({commit},data) {
        let result = await reqLoginUser(data)
        if (result.data.code == 200) {
            commit("LOGINUSER", result.data.data.token)
            setToken(result.data.data.token)
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }        
    },
    async getUserInfo({commit}) {
        let result = await reqGetUserInfo()
        if (result.data.code == 200) {
            commit("GETUSERINFO", result.data.data)
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async userLogout({commit}) {
        let result = await reqLogout();
        if (result.data.code == 200) {
            commit("CLEAR");
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    }
}
const mutations = {
    GETCODE(state,code) {
        state.code=code
    },
    LOGINUSER(state,token) {
        state.token=token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo=userInfo
    },
    CLEAR(state) {
        state.token=""
        state.userInfo = {}
        removeToken();
    }
}
const getters = {}
export default {
    state,
    actions,
    mutations,
    getters
}